package com.jinyou.utils.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

public class HttpUploadUtil {

    public static String httpClient(String url, Map<String, String> textMap,
                                    String fieldName, String fileName, InputStream inputStream) throws ClientProtocolException, IOException {
        HttpClient context = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create().setMode(HttpMultipartMode.RFC6532);
        //MultipartEntityBuilder builder = MultipartEntityBuilder.create();

        for (Entry<String, String> param : textMap.entrySet()) {
            builder.addTextBody(param.getKey(), param.getValue(), ContentType.TEXT_PLAIN);
        }

        if (null == fileName) {
            fieldName = "";
        }
        if (null != inputStream) {
            builder.addBinaryBody(fieldName, inputStream, ContentType.MULTIPART_FORM_DATA, fileName);
        }

        post.setEntity(builder.build());
        HttpResponse response = context.execute(post);

        String re = new String(EntityUtils.toByteArray(response.getEntity()));

        return re;
    }


    public static void main(String[] args) {
        try {
//            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//            MultipartFile coverFile = multipartRequest.getFile("file");
            File file = new File("E://1.jpg");
            InputStream is = new FileInputStream(file);


            String url = "http://o2o3.waimai101.com/jyimg/upload/imgs/up";
            Map<String, String> textMap = new HashMap<>();
            textMap.put("fileFullPathName", "/usr/local/jars/2.png");
            HttpUploadUtil.httpClient(url, textMap, "image", null, is);

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}
